<?php
/**************************************************************************
 * Naanal PHP Framework, Simple, Efficient and Developer Friendly
 * Ver 3.0, Copyright (C) <2010>  <Tamil Amuthan. R>
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 ************************************************************************/

function currentPage($page=null)
{
    static $currentpage=null;
    if(is_null($page))
    {
        return $currentpage;
    }
    $currentpage=$page;
}
function pageDetails($page,$action=null,$switch="default")
{
    static $arrPage=null;
    if(is_null($action)) 
    {
        return $arrPage[$page];
    }
    $arrPage[$page]=array("action"=>$action,"switch"=>$switch);
}
class ClsNaanalPage extends ClsLInputValidator
{ 
    private $pdo=null;
    private $objAuthentication=null;
    private $errUnexpected="unexpected error. please contact your software vendor";
    protected $page=null;
    protected $mode=null;
    public $controlPanel=null;
    public $encryptURL=null;
    public $ipFilterControlpanel=null;
    public $homepage=null;
    public $fldUserID="userid";
    public $fldUser="name";
    public $fldPassword="password";
    ///if true, a submit button will appended to the form automatically.
    public $isAutoSubmitButton=true;
    public $isDOMTemplate=false;
    public $arrPageForDOMTemplate=null;
    ///associative array key as page name and value as mode. the page set in this array will bypass authentication process
    public $overrideAuthentication=array("user"=>"create");
    
    protected $arrError=array();
    
    public function __construct($controlPanel,$encryptURL=false,$ipFilterControlpanel=null,$homepage="index.php")
    {
        $this->controlPanel=$controlPanel;
        parent::__construct($this->controlPanel,$this->encryptURL,$this->ipFilterControlpanel,$this->homepage);
        $this->encryptURL=$encryptURL;
        $this->ipFilterControlpanel=$ipFilterControlpanel;
        $this->homepage=$homepage;

        $this->objNaanalRequest->setData("loginip",$this->userIP);
        if($this->objNaanalRequest->isDataSet("err"))
        {
            $code=$this->objNaanalRequest->getData("err");
            errMsg($code);
        }
    } 

    public function logout()
    {
        if(empty(ClsConfig::$CONTROL_PANEL))
        {
            return true;
        }
        $loginPanel=getLoginControlPanel();
        $loginTable=ClsConfig::$CONTROL_PANEL[$loginPanel]["table"]["login"];
        $loginHomeModule=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["home"]["module"];
        $loginHomeAction=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["home"]["action"];
        $loginPage=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["module"];
        $loginAction=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["action"];
        $dbname= getAppConfig("DATABASE_NAME");//ClsConfig::$CONTROL_PANEL[$loginPanel]["database"];
        $dbuser= getAppConfig("DATABASE_USER");// ClsConfig::$DATABASE[$dbname]["user"];
        $dbpass= getAppConfig("DATABASE_PASSWORD");// ClsConfig::$DATABASE[$dbname]["password"];
        $authPDO=  ClsNaanalPDO::getNamedInstance($dbname, $dbname, $dbuser, $dbpass);
        $this->objAuthentication=new ClsNaanalAuthentication($authPDO,  $loginTable);
        $this->objAuthentication->setControlPanel($loginPanel);
        $this->objAuthentication->fldUserID=$this->fldUserID;
        $this->objAuthentication->fldUser=$this->fldUser;
        $this->objAuthentication->fldPassword=$this->fldPassword;
        $this->objAuthentication->logout();
        header("Location:index.php?page={$loginHomeModule}&action={$loginHomeAction}");exit;
    }
    
    /**
    * 
    * if already logged in, it returns true
    * else it validates the login and do accordingly
    * @param unknown_type $objRequest
    * @param unknown_type $isLock
    */
    public function authenticate()
    {
        if(empty(ClsConfig::$CONTROL_PANEL))
        {
            return true;
        }
        $loginPanel=getLoginControlPanel();
        $loginTable=ClsConfig::$CONTROL_PANEL[$loginPanel]["table"]["login"];
        $loginHomeModule=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["home"]["module"];
        $loginHomeAction=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["home"]["action"];
        $loginPage=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["module"];
        $loginAction=ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["action"];
        $loginSubmit=isset(ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["submit"])?ClsConfig::$CONTROL_PANEL[$loginPanel]["page"]["login"]["submit"]:false;
        $dbname= getAppConfig("DATABASE_NAME");//ClsConfig::$CONTROL_PANEL[$loginPanel]["database"];
        $dbuser= getAppConfig("DATABASE_USER");// ClsConfig::$DATABASE[$dbname]["user"];
        $dbpass= getAppConfig("DATABASE_PASSWORD");// ClsConfig::$DATABASE[$dbname]["password"];
        $authPDO=  ClsNaanalPDO::getNamedInstance($dbname, $dbname, $dbuser, $dbpass);
        $this->objAuthentication=new ClsNaanalAuthentication($authPDO,  $loginTable);
        $this->objAuthentication->setControlPanel($loginPanel);
        $this->objAuthentication->fldUserID=$this->fldUserID;
        $this->objAuthentication->fldUser=$this->fldUser;
        $this->objAuthentication->fldPassword=$this->fldPassword;
        if(!isset(ClsConfig::$DATABASE_WRAPPER_CLASS) || ClsConfig::$DATABASE_WRAPPER_CLASS)
        {
            $objUser=  ClsWrapper::getInstance($loginPage);
            $staticError=ClsWrapper::getStaticError();
            if($staticError)
            {if($loginTable!="user")
                trace("Unable to load '{$loginTable}' object");
            }
        }
        if($this->objNaanalRequest->getModule()=="user" && $this->objNaanalRequest->getAction()=="logout")
        {
            if(isLogged())
            {
                $this->objAuthentication->logout();	
                header("Location:index.php?page={$loginHomeModule}&action={$loginHomeAction}");exit;
            }
        }
        else if($this->objNaanalRequest->getModule()=="logout")
        {
            if(isLogged())
            {
                $this->objAuthentication->logout();	
                header("Location:index.php?page={$loginHomeModule}&action={$loginHomeAction}");exit;
            }
        }
        else if(!isLogged())
        {
            if($this->objNaanalSession->getLoginPanel() == $loginPanel) return true;
            $isLoginSkip=false;

            $actiontmp=$this->objNaanalRequest->isDataSet("action")?$this->objNaanalRequest->getData("action"):"create";
            
            if(array_key_exists($this->objNaanalRequest->getModule(), $this->overrideAuthentication) && in_array($actiontmp,$this->overrideAuthentication[$this->objNaanalRequest->getModule()]))
            {
                $isLoginSkip=true;
            }
            if($this->objNaanalSession->getLoginID()>0 || $isLoginSkip)
            {
                $this->page=$this->objNaanalRequest->getModule();
                $this->module=$this->page;
                $this->action=$actiontmp;
            }
            else
            {
                if(!$this->objNaanalRequest->isDataSet($this->fldUserID))
                {
                    $this->page=$loginPage;
                    $this->action=$loginAction;
                    $this->module=$loginPage;
                }
                else
                {
                    if($loginSubmit===false)
                    {
                        $success=$this->objAuthentication->authenticate($this->objNaanalRequest->getData($this->fldUserID),$this->objNaanalRequest->getData("password"));
                        if($success)
                        {
                            $this->module="home";
                            $this->action="create";
                            $this->controlPanel=$loginPanel;
                            return true;
                        }
                        else
                        {
                            $this->module=$loginHomeModule;
                            $this->action=$loginHomeAction;
                            errMsg("UserID or Password Wrong");
                            return false;
                        }
                    }
                    else
                    {
                        $this->module=$loginPage;
                        $this->action=$loginSubmit;
                    }
                }
            }
        }
        return true;
    }
    public function loadPDO($host,$user,$pass,$dbname,$sqlserver="mysql")
    {
        $this->pdo=ClsNaanalPDO::getInstance($host,$user,$pass,$dbname,$sqlserver);		
    }

    public function &getPDO()
    {
            return $this->pdo;		
    }
    
    public function getError()
    {
        return $this->arrError;
    }
 
    public function render()
    {
        $forModule=$this->module;
        $forAction=$this->action;
        $this->overrideAuthentication=array('addcompany'=>array('create'));

        /**
         *  if dynamicdatabase is set, the dynamicdatabase is picked automatically while login
         */
        $this->overrideAuthentication['modconfig']=array('create');
        $this->overrideAuthentication['install']=array('create','wizard');
        $this->overrideAuthentication['appconfig']=array('create');
        $this->overrideAuthentication['download']=array('create');
        $this->overrideAuthentication['client']=array('create','insert','registered');
        
        if(ClsNaanalApplication::$isApplicationHasError)
        {
            if (!isFrameworkInstalled())
            {
                if($this->module=="install")
                {
                    $objInstallModule = get_module_object($this->module,$this->action);
                    if($objInstallModule===false)
                    {
                        die("Framework not installed properly. Module install does not exist");
                    }
                    if(ClsNaanalRequest::getInstance()->isSubmit()) 
                    {
                        $objInstallModule->setSubmit();
                    }
                    $out=$objInstallModule->render();
                }
                else
                {
                    $objInstallModule = get_module_object("install");
                    if(ClsNaanalRequest::getInstance()->isSubmit()) 
                    {
                        $objInstallModule->setSubmit();
                    }
                    $out=$objInstallModule->render();
                }
                echo $out;
                $success = false;
            }
            else if(!isApplicationInstalled())
            {
                if(!file_exists("modules/install"))
                {
                    $success=false;
                    die("Application not installed properly. Module install does not exist");
                }
                else
                {
                    if($this->module=="install")
                    {
                        
                    }
                    else
                    {
                        $this->module="install";
                        $this->page="install";
                        $this->action="create";
                        $this->mode="create";
                    }
                    
                    $success = false;
                }
            }
            else
            {
                $objConfiggenModule=get_module_object("appconfig");
                if(ClsNaanalRequest::getInstance()->isSubmit()) 
                {
                    $objConfiggenModule->setSubmit();
                }
                $out=$objConfiggenModule->render();
                $moduleTheme=$objConfiggenModule->getConfigVar("theme");
                $objLTheme=ClsLTheme::getInstance("default");
                if(!ClsNaanalApplication::$isApplicationHasError) $objLTheme->setErrorMessage(errMsg());
                $objLTheme->setTemplateVariable("controlpanel", $this->controlPanel);
                $objLTheme->setTemplateVariable("homepage", $this->homepage);
                echo $objLTheme->render($out);
                $success=false;
            }
        }
        if(! class_exists("ClsConfig")) return;
        /**
         * If application does not has error or if the module is install
         */
        if(!ClsNaanalApplication::$isApplicationHasError || $this->module=="install")
        {
            addLog("Server started at ".date("d-m-Y H:i:s",time()));
            if(IS_NAANAL_ADMIN===false && isset(ClsConfig::$DATABASE) && ClsConfig::$DATABASE) 
            {
                if(empty(ClsConfig::$DATABASE))
                {
                    die("Database Not Set");
                }
                else
                {
                    if(is_array(ClsConfig::$DATABASE))
                    {
                        foreach(ClsConfig::$DATABASE as $dbname=>$arrData)
                        {
                            ClsNaanalPDO::getNamedInstance($dbname, $dbname, $arrData["user"], $arrData["password"], $arrData["server"], $arrData["host"]);
                        }
                    }
                    else
                    {
                        ClsNaanalPDO::getNamedInstance(getAppConfig("DATABASE_NAME"), getAppConfig("DATABASE_NAME"), getAppConfig("DATABASE_USER"), getAppConfig("DATABASE_PASSWORD"), getAppConfig("DATABASE_SERVER"), getAppConfig("DATABASE_HOST"));
                    }
                }
            }
            if(IS_NAANAL_ADMIN===false && getAppConfig("DATABASE_NAME"))
            {
                ClsNaanalPDO::getNamedInstance(getAppConfig("DATABASE_NAME"), getAppConfig("DATABASE_NAME"), getAppConfig("DATABASE_USER"), getAppConfig("DATABASE_PASSWORD"), getAppConfig("DATABASE_SERVER"), getAppConfig("DATABASE_HOST"));
            }
            processEntry();
            ClsPageDetail::$PAGE=$this->module;
            ClsPageDetail::$ACTION=$this->action;
            ClsPageDetail::$SWITCH=$this->objNaanalRequest->isDataSet("switch")?$this->objNaanalRequest->getData("switch"):"default";
            $this->overrideAuthentication["modconfig"]=array("create");
            $this->overrideAuthentication["appconfig"]=array("create");
            $this->overrideAuthentication['user']=array('forgot');
            $id=$this->objNaanalRequest->getID();
            if(isset(ClsConfig::$DATABASE) && ClsConfig::$DATABASE)
            {
                ///if control panel exist
                if(ClsConfig::$CONTROL_PANEL)
                {
                    /**
                     * if client id exist, relevent client is loaded. else client default loaded
                     */
                    $client_id=ClsNaanalSession::getInstance()->getPanelData("client_id");
                    if($client_id)
                    {
                        $objClient=ClsWrapper::getInstance("client");
                        $objClient->loadObject($client_id);
                        $company=$objClient->get_company();
                    }
                    else
                    {
                        $company="default";
                    }
                    if(file_exists(NAANAL_APP_PATH."client/{$company}/utils.php"))
                    {
                        include_once(NAANAL_APP_PATH."client/{$company}/utils.php");
                    }
                }
            }
            $objLibModule=get_module_object($this->module, $this->action, $id);
            if($objLibModule===false)
            {
                $this->arrError[]="module($this->module), action($this->action), switch($this->switch) not valid";
                trace($this->arrError);
                return false;
            }
            if($objLibModule!==false && $objLibModule->isModule())
            {
                $objLibModule->setSwitch($this->switch);
                if(ClsNaanalRequest::getInstance()->isSubmit()) 
                {
                    $objLibModule->setSubmit();
                }
                /**
                 * store original page and mode. Authentication process might change the page or mode
                 */
                $oldPage=$this->module;
                $oldMode=$this->action;
                $control_panel=$objLibModule->getConfigVar("control_panel");
                $isAuthenticationNeeded=$objLibModule->getConfigVar("is_authentication_needed");
                if(IS_NAANAL_ADMIN===false && isApplicationInstalled()) 
                {
                    if($control_panel===false || $control_panel==="guest")
                    {
                        if(function_exists("onAppInit"))
                        {
                            onAppInit();
                        }
                    }
                    /*else if($control_panel===true)
                    {
                        if($isAuthenticationNeeded===true)
                        {
                            $success=$this->authenticate();
                            if(!$success) 
                            {
                                errMsg("UserID or Password Wrong");
                                header("Location:index.php");exit;
                            }
                        
                            if(function_exists("onAppInit"))
                            {
                                onAppInit();
                            }
                            if($this->module==$oldPage && $this->action==$oldMode)
                            {}
                            else
                                $objLibModule=get_module_object($this->module, $this->action, $id);
                        }
                        else
                        {
                            if(function_exists("onAppInit"))
                            {
                                onAppInit();
                            }
                        }
                    }*/
                    else if(isLogged () && $this->module=="user" && $this->action=="logout")
                    {
                        $this->logout();	
                    }
                    else
                    {
                        $success=$this->authenticate();
                        if(!$success) 
                        {
                            errMsg("UserID or Password Wrong");
                            header("Location:index.php");exit;
                        }
                        if(function_exists("onAppInit"))
                        {
                            onAppInit();
                        }
                        if($this->module==$oldPage && $this->action==$oldMode)
                        {
                        }
                        else
                        {
                            if(empty($this->module) || empty($this->action))
                            {
                                trace("the module is modified or action is modified as empty for $oldPage module and $oldMode action. new module:{$this->module}, new action:{$this->action}");
                            }
                            else
                            {
                                $objLibModule=get_module_object($this->module, $this->action, $id);
                            }
                        }
                    }
                }
            }
            else
            {
                if(function_exists("onAppInit"))
                {
                    onAppInit();
                }
            }
            $isTemplateNo=false;
            if(isset(ClsConfig::$NO_TEMPLATE))
            {
                foreach(ClsConfig::$NO_TEMPLATE as $arrNoTemplate)
                {
                    if(isset($arrNoTemplate["module"]) && $arrNoTemplate["module"]==$this->module)
                    {
                        if(isset($arrNoTemplate["action"]))
                        {
                            if($arrNoTemplate["action"]==$this->action)
                            {
                                if(isset($arrNoTemplate["switch"]))
                                {
                                    if($arrNoTemplate["switch"]==$this->switch)
                                    {
                                        $isTemplateNo=true;
                                    }
                                }
                                else
                                {
                                    $isTemplateNo=true;
                                }
                            }
                        }
                        else
                        {
                            $isTemplateNo=true;
                        }
                    }
                }
            }
            if($objLibModule!==false) 
            {
                $out=$objLibModule->render();
                $moduleTheme=$objLibModule->getConfigVar("theme");
                $actionTheme=$objLibModule->getConfigVar("actions");
                if(isset($actionTheme[$this->action]["theme"]))
                {
                    $moduleTheme=$actionTheme[$this->action]["theme"];
                }
            }
            else
            {
                $moduleTheme=false;
            }
            if(isset($this->request["msg"]))
            {
                $out=$this->request["msg"]."<br />".$out;
            }
            if($isTemplateNo===true)
            {
                $moduleTheme=false;
            }
            
                if($moduleTheme===false)
                {
                    $themeToApply=false;
                }
                else if(is_null($moduleTheme) || $moduleTheme===true)
                {
                    if(class_exists("ClsConfig") && isset(ClsConfig::$theme) && !empty(ClsConfig::$theme))
                    {
                        $themeToApply=  ClsConfig::$theme;
                    }
                    else
                    { 
                        $themeToApply="default";
                    }
                }
                else
                {
                    $themeToApply=$moduleTheme;
                }
                $objLTheme=ClsLTheme::getInstance($themeToApply);
                $objLTheme->setForModule($forModule);
                $objLTheme->setForAction($forAction);
                $objLTheme->setModuleObject($objLibModule);
                $objLTheme->setControllerObject($objLibModule->getControllerObject());
                $objLTheme->setTemplateVariable("controlpanel", $this->controlPanel);
                $objLTheme->setTemplateVariable("homepage", $this->homepage);
                /**
                 * module menus should not be called when the application is in install mode
                 */
                if($objLibModule->getModule()!="install")
                {
                    $objMenu=ClsNaanalMenu::getInstance("menu");
                    $NAANAL_MENU=$objMenu->getModuleMenus();
                    $objLTheme->setTemplateVariable("NAANAL_MENU",$NAANAL_MENU);
                }
                if(isset($out)) echo $objLTheme->render($out);
                $this->objNaanalRequest->render();
                $this->objNaanalPost->render();
                $this->objNaanalGet->render();
                $autoSession=getConfigVar("AUTO_SESSION");
                if(!($autoSession===false))
                {
                    $this->objNaanalSession->render();
                }
           // }
        }
        processExit();
    }
}
?>